package com.wy.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author wangyong
 */
public class TcpMessageHandler extends ChannelInboundHandlerAdapter {
    private final Channel clientChannel;

    public TcpMessageHandler(Channel channel) {
        this.clientChannel = channel;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf readBuffer = (ByteBuf) msg;
        clientChannel.writeAndFlush(readBuffer).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        if (clientChannel != null && clientChannel.isActive()) {
            clientChannel.close();
        }
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        if (clientChannel != null && clientChannel.isActive()) {
            clientChannel.close();
        }
    }

}

